package com.stu.service;

import com.alibaba.fastjson.JSON;
import com.stu.bean.CategoryEntity;
import com.stu.vo.Catelog2Vo;
import io.swagger.annotations.ApiModel;
import lombok.*;
import org.apache.commons.io.FileUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: MI
 * @Date: 2021/8/17/6:31
 * @Description:
 */

/*************************************************
 *Cacheable
 *CacheEvict 同时进行多种缓存操作
 */

@Service
public class RedisService {
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @ApiModel(value = "缓存测试map-bean", description = "用来做测试的 map vo")
    public static class MapVo {
        private int id;
        private String name;
    }

    static Map<String, MapVo> map = new HashMap();

    static {
        map.put("1", new MapVo(1, "tom"));
        map.put("2", new MapVo(2, "luck"));
    }

    @Cacheable(value = "cache:map", key = "#root.methodName")
    public Map map() {
        return map;
    }

    /**
     * 级联更新所有关联的数据
     * CacheEvict失效模式：
     * 1 同时删除多种缓存操作 Caching
     * 2 指定删除某个分区下所有数据 CacheEvict
     * 3 存储同一类型的数据，都可以指定同一分区，分区名默认是缓存的前缀
     * <p>
     * 如果key是字符串， 添加单引号，否则认为是动态取值。
     */
    // @CacheEvict(value = "getcate", key = "'getDataFromDb'")
    //删除缓存分区下所有数据
    @CacheEvict(value = "getcate", allEntries = true)
    @Caching(evict = {
            @CacheEvict(value = "getcate", key = "'getDataFromDb'")
    })
    public void delCache() {
    }

    @Cacheable(value = "getcate", key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getDataFromDb() throws IOException {
        /**
         * 将数据库的多次查询变为一次
         */
        List<CategoryEntity> selectList = this.selectList();

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));
        return parentCid;
    }

    /**
     * 从文本中 读取 模拟 读取数据库
     *
     * @return 集合
     * @throws IOException 文件找不到
     */
    private List<CategoryEntity> selectList() throws IOException {
        final String s = FileUtils.readFileToString(ResourceUtils.getFile("classpath:test.json"),
                StandardCharsets.UTF_8);
        final List<CategoryEntity> list = JSON.parseArray(s, CategoryEntity.class);
        return list;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
    }

    @SneakyThrows
    @Cacheable(value = "all", key = "'ss'")
    public List<CategoryEntity> cacheKey() {
        System.out.println("读取文件了");
        final String s = FileUtils.readFileToString(ResourceUtils.getFile("classpath:test.json"),
                StandardCharsets.UTF_8);
        final List<CategoryEntity> list = JSON.parseArray(s, CategoryEntity.class);
        return list;
    }
}
